﻿using System.IO;
using UnityEngine;
using Newtonsoft.Json;

/// <summary>
/// 游戏信息系统（单例）
/// 管理英雄数据、地图进度、存档/读档
/// </summary>
public class InfoSystem : PersistentSingleton<InfoSystem>
{
    [JsonProperty(TypeNameHandling = TypeNameHandling.All)]
    public Hero hero = null;

    public int nowMapItemId;
    public int mapStep;
    public int mapBanStep;
    public int mapBanStepWait;
    public string seed;
    public int callCount;

    private string saveFilePath => Path.Combine(Application.persistentDataPath, "savegame.json");


    public void SaveGame()
    {
        if (hero == null)
        {
            Debug.LogWarning("没有Hero数据，无法保存");
            return;
        }

        var saveData = new SaveData
        {
            hero = this.hero,
            nowMapItemId = this.nowMapItemId,
            mapStep = this.mapStep,
            mapBanStep = this.mapBanStep,
            mapBanStepWait = this.mapBanStepWait,
            seed = this.seed,
            callCount = this.callCount
        };

        var settings = new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.All,
            Formatting = Formatting.Indented
        };

        string json = JsonConvert.SerializeObject(saveData, settings);
        File.WriteAllText(saveFilePath, json);

        Debug.Log($"存档成功 -> id={nowMapItemId}, step={mapStep}, 卡牌数={hero.Cards.Count}, 道具数={hero?.Relics?.Count ?? 0}, 路径={saveFilePath}");
    }

    /// <summary>
    /// 读取存档，还原 hero 和所有 InfoSystem 字段
    /// </summary>
    public void LoadGame()
    {
        if (!File.Exists(saveFilePath))
        {
            Debug.LogWarning("存档文件不存在，不能读取");
            return;
        }

        var settings = new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.All
        };

        string json = File.ReadAllText(saveFilePath);
        var saveData = JsonConvert.DeserializeObject<SaveData>(json, settings);

        if (saveData != null)
        {
            hero = saveData.hero;
            nowMapItemId = saveData.nowMapItemId;
            mapStep = saveData.mapStep;
            mapBanStep = saveData.mapBanStep;
            mapBanStepWait = saveData.mapBanStepWait;
            seed = saveData.seed;
            callCount = saveData.callCount;

            Debug.Log($"读档成功 -> id={nowMapItemId}, step={mapStep}, 卡牌数={hero.Cards.Count}, 道具数={hero?.Relics?.Count ?? 0}");
        }
        else
        {
            Debug.LogWarning("读档失败，SaveData 为 null");
        }
    }

    /// <summary>
    /// 存档数据结构
    /// </summary>
    private class SaveData
    {
        public Hero hero;
        public int nowMapItemId=0;
        public int mapStep=0;
        public int mapBanStep=0;
        public int mapBanStepWait=3;
        public string seed;
        public int callCount;
    }
    public void ResetInfo()
    {
        nowMapItemId = 0;
        mapStep = 0;
        mapBanStep = 0;
        mapBanStepWait = 2;
        Tool.ResetTool();
    }
}
